<?php

namespace app\admin\service;

use app\admin\dao\LawCaseCategoryDao;
use app\admin\model\UM as UM;
use app\common\model\LawCaseCategory;
use ShidianUtil\Exception\DataNotExistException;
use think\Collection;
use think\exception\ValidateException;

/**
 * 案件类型
 * Class LawCaseCategoryService
 * @package app\admin\service
 */
class LawCaseCategoryService
{
    // dao
    private LawCaseCategoryDao $lawCaseCategoryDao;

    public function __construct(LawCaseCategoryDao $lawCaseCategoryDao)
    {
        $this->lawCaseCategoryDao = $lawCaseCategoryDao;
    }

    public function indexOptions(): Collection
    {
        return $this->lawCaseCategoryDao->selectOptions();
    }

    /**
     * 列表
     * @param UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return array
     */
    public function index(?UM $user, ?int $page = null, ?int $page_size = null): array
    {
        return $this->lawCaseCategoryDao->listCategories($page, $page_size);
    }

    /**
     * 查询
     * @param UM|null $user
     * @param int $id
     * @return LawCaseCategory
     */
    public function read(?UM $user, int $id): ?LawCaseCategory
    {
        return $this->lawCaseCategoryDao->findCategory($id);
    }

    /**
     * 新增
     * @param UM $user
     * @param array $params
     * @return  LawCaseCategory
     */
    public function add(UM $user, array $params): LawCaseCategory
    {
        $params['userId'] = $user->id;

        $this->checkRepeat($params['name']);

        return $this->lawCaseCategoryDao->insertActive($params, []);
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return LawCaseCategory
     */
    public function modify(UM $user, int $id, array $params): LawCaseCategory
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = LawCaseCategory::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该对象不存在或已被删除');
        }

        $this->checkRepeat($params['name'], $id);

        $allowField = ['name', 'ord', 'remarks', 'smallPic'];
        $this->lawCaseCategoryDao->updateActive($record, $params, $allowField);

        return $record;
    }

    /**
     * 删除
     * @param UM $user
     * @param int $id
     */
    public function rm(UM $user, int $id): void
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = LawCaseCategory::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            return;
        }

        $this->lawCaseCategoryDao->deleteModel($record);
    }

    private function checkRepeat($name, $id = null)
    {
        $record = LawCaseCategory::where('name', $name)
            ->when(is_id($id), function ($query) use ($id) {
                $query->where('id', '<>', $id);
            })
            ->find();

        if (!is_null($record)) {
            throw new ValidateException('该案件类型已存在');
        }
    }
}
